
//
//  KSelectCommunityController.m
//  Keping
//
//  Created by 柯平 on 2017/10/11.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KSelectCommunityController.h"
#import "KGpsCommunityRequest.h"
#import <CoreLocation/CoreLocation.h>
#import "KCommunityEntityViewData.h"

@interface KSelectCommunityController ()<UITextFieldDelegate,CLLocationManagerDelegate>
{
    CLLocationManager *_locationManager;
    CLLocationCoordinate2D _currentLocationCoordinate;
    NSString* _name;
}

/**/
@property(nonatomic,strong)UITextField* searchView;
/**/
@property(nonatomic,strong)YYLabel* locationLabel;
/**/
@property(nonatomic,strong)UIButton* locationButton;

@end

@implementation KSelectCommunityController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self startLocation];
    self.title = @"Select Community";
    self.view.backgroundColor = KBackColor;
    
    //
    _searchView = [[UITextField alloc] init];
    _searchView.delegate = self;
    _searchView.backgroundColor = kWhiteColor;
    [_searchView setFrame:CGRectMake(0, 0, kScreenWidth, 54)];
    _searchView.placeholder = @"Search by community name";
    UIImage* searchImg = [[UIImage imageNamed:@"search_icon"] imageByResizeToSize:CGSizeMake(14, 14)];
    UIImageView* leftView = [[UIImageView alloc] init];
    leftView.image = searchImg;
    leftView.size = CGSizeMake(34, 14);
    leftView.contentMode = UIViewContentModeCenter;
    _searchView.leftViewMode = UITextFieldViewModeAlways;
    _searchView.leftView = leftView;
    [self.view addSubview:_searchView];
    
    UIView* locationView = [[UIView alloc] initWithFrame:CGRectMake(0, _searchView.bottom+10, kScreenWidth, 94)];
    locationView.backgroundColor = kWhiteColor;
    [self.view addSubview:locationView];
    
    _locationLabel = [YYLabel new];
    NSMutableAttributedString* locationText = [[NSMutableAttributedString alloc] initWithString:@"Current location" attributes:@{NSFontAttributeName:SystemSmallFont,NSForegroundColorAttributeName:kDarkGrayColor}];
    UIImage* locateImg = [UIImage imageNamed:@"search_location"];
    NSMutableAttributedString* locationImg = [NSMutableAttributedString imageStringWithFontSize:16 image:locateImg];
    [locationText insertAttributedString:locationImg atIndex:0];
    [locationText insertString:@"   "atIndex:0];
    [locationText appendString:@"   "];
    _locationLabel.attributedText = locationText;
    [_locationLabel setFrame:CGRectMake(0, 0, locationView.width, 40)];
    [locationView addSubview:_locationLabel];
    
    _locationButton = [UIButton commonButtonWithTitle:@"LBS location"];
    [_locationButton setFrame:CGRectMake(15, _locationLabel.bottom, locationView.width-30, 44)];
    [_locationButton addTarget:self action:@selector(startLocation) forControlEvents:UIControlEventTouchUpInside];
    [locationView addSubview:_locationButton];
    
    self.tableView.sectionHeaderHeight = 54;
    [self.tableView setFrame:CGRectMake(0, CGRectGetMaxY(locationView.frame), kScreenWidth, kScreenHeight-CGRectGetMaxY(locationView.frame))];
}

-(void)refresh
{
    [super refresh];
    self.page = 1;
    [self getData];
}

-(void)loadmore
{
    [super loadmore];
    self.page++;
    [self getData];
}

-(void)getData
{
    [super getData];
    NSString *type;
    if (_name) {
        type = @"name";
    } else {
        type = @"lbs";
    }
    KGpsCommunityRequest* request = [[KGpsCommunityRequest alloc] init];
    request.params = [NSDictionary dictionaryWithObjectsAndKeys:
                      @(_currentLocationCoordinate.latitude),@"latitude",
                      @(_currentLocationCoordinate.longitude),@"longitude",
                      _name?:@"",@"name",
                      @(self.page),@"page",
                      @(self.pageSize),@"pageSize",
                      @"community",type, nil];
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        KCommunityEntityViewData* data = [KCommunityEntityViewData modelWithJSON:request.responseData];
        if (data.statusCode == 200) {
            if (self.page == 1) {
                [self.data removeAllObjects];
            }
            [self.data addObjectsFromArray:
             data.communityEntityViews];
        }else{
            [self showErrorText:data.msg errCode:data.statusCode];
        }
        [self.tableView endRefresh];
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [self.tableView endRefresh];
    }];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* view = [UIView new];
    UILabel* titleLb = [UILabel new];
    view.backgroundColor = KBackColor;
    titleLb.text = @"Nearby communities";
    [titleLb setFrame:CGRectMake(15, 20, kScreenWidth-30, 24)];
    titleLb.textColor = kDarkGrayColor;
    titleLb.font = SystemSmallFont;
    [view addSubview:titleLb];
    return view;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KCommunityEntityView* model = self.data[indexPath.row];
    KTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:[KTableViewCell className]];
    if (!cell) {
        cell = [[KTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[KTableViewCell className]];
    }
    cell.textLabel.text = model.name;
    cell.textLabel.font = SystemFont;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    KCommunityEntityView* model = self.data[indexPath.row];
    self.entity(model);
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)startLocation
{
    [self.view endEditing:YES];
    if([CLLocationManager locationServicesEnabled]){
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.distanceFilter = 5;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            [_locationManager requestWhenInUseAuthorization];
        }
        //开始定位，不断调用其代理方法
        [_locationManager startUpdatingLocation];
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    // 1.获取用户位置的对象
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
    NSLog(@"纬度:%f 经度:%f", coordinate.latitude, coordinate.longitude);
    
    [[KAppConfig sharedConfig] setLatitude:coordinate.latitude];
    [[KAppConfig sharedConfig] setLongitude:coordinate.longitude];
    _currentLocationCoordinate = coordinate;
    
    // 2.停止定位
    [manager stopUpdatingLocation];
    
    //3.请求附近的社区
    [self.tableView beginRefresh];
}

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [_locationManager requestWhenInUseAuthorization];
            }
            break;
        case kCLAuthorizationStatusDenied:
        {
        }
            
        default:
            break;
    }
}

#pragma mark - UITextfieldDelegate
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    _name = textField.text;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
